package com.niit.service.impl;

import com.niit.entity.Message;
import com.niit.entity.MessageObject;
import com.niit.repository.MessageObjectRepository;
import com.niit.repository.MessageRepository;
import com.niit.repository.UserRepository;
import com.niit.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 张月
 * @apiNote
 */
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageRepository messageRepository;
    @Autowired
    private MessageObjectRepository messageObjectRepository;
    @Autowired
    private UserRepository userRepository;

    @Override
    public Message sendMessage(Message message) {
        message.setSendTime(LocalDateTime.now());
        message.setIsRead(false);
        return messageRepository.save(message);
    }

    @Override
    public List<Message> getChatMessages(Integer senderId, Integer receiverId) {
        MessageObject msg1 = messageObjectRepository.findAllBySender_IdAndReceiver_Id(senderId, receiverId);
        MessageObject msg2 = messageObjectRepository.findAllBySender_IdAndReceiver_Id(receiverId, senderId);
        List<Integer> messages = new ArrayList<>();
        if(msg1 != null) messages.add(msg1.getId());
        if(msg2 != null) messages.add(msg2.getId());
        return messageRepository.findAllByMessageObject_IdInOrderBySendTimeAsc(messages);
    }
    @Override
    public MessageObject findOrCreateMessageObject(Integer senderId, Integer receiverId) {
        // 先检查是否已存在对话关系
        MessageObject messageObject = messageObjectRepository.findAllBySender_IdAndReceiver_Id(senderId, receiverId);

        if (messageObject == null) {
            // 如果不存在，创建新的对话关系
            messageObject = new MessageObject();
            messageObject.setSender(userRepository.findById(senderId).orElseThrow(() -> new RuntimeException("用户不存在")));
            messageObject.setReceiver(userRepository.findById(receiverId).orElseThrow(() -> new RuntimeException("用户不存在")));
            messageObject.setStatus(false); // 默认未拉黑
            messageObject.setCreateTime(LocalDateTime.now());
            messageObject = messageObjectRepository.save(messageObject);
        }

        return messageObject;
    }

    @Override
    public boolean checkBlockStatus(Integer senderId, Integer receiverId) {
        // 检查是否被对方拉黑
        MessageObject messageObject = messageObjectRepository.findAllBySender_IdAndReceiver_Id(senderId, receiverId);
        return messageObject != null && Boolean.TRUE.equals(messageObject.getStatus());
    }

    @Override
    public void markAsRead(Integer messageId) {
        Message message = messageRepository.findById(messageId).orElse(null);
        if (message != null) {
            message.setIsRead(true);
            messageRepository.save(message);
        }
        else {
            throw new RuntimeException("消息不存在");
        }
    }

    @Override
    public void deleteMessage(Integer messageId) {
        // 消息发出后超过两分钟不能撤回
        Message message = messageRepository.findById(messageId).orElse(null);
        if (message != null && LocalDateTime.now().isAfter(message.getSendTime().plusMinutes(2))) {
            throw new RuntimeException("消息已超过两分钟，不能撤回");
        }else {
            messageRepository.deleteById(messageId);
        }
    }
    @Override
    public List<Message> findBySenderId(Integer senderId) {
        return messageRepository.findLastMessagesPerPeer(senderId);
    }
}
